package cn.wuxun.search.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.Transport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;

import cn.wuxun.common.pojo.News;
import cn.wuxun.common.utils.MapperUtil;
import cn.wuxun.search.mapper.SearchMapper;

@Service
public class SearchService {
	@Autowired
	private SearchMapper searchMapper;

	@Autowired
	private TransportClient client;

	public void createWXindex() throws JsonProcessingException {
		// 读取新闻数据
		List<News> nList = searchMapper.queryAllNewsTitle();
		
		// 通过es存储到WX_index索引文件中
		for (News news : nList) {
			// 转化成Json字符串
			String json = MapperUtil.MP.writeValueAsString(news);
			IndexRequestBuilder request = client.prepareIndex("wx_index", "news", news.getNid());
			request.setSource(json).get();
		}
	}

	public List<News> queryNews(String query) {
		// 创建一个查询条件query
		MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", query);
		SearchResponse response = client.prepareSearch("wx_index").setQuery(matchQuery).get();
		// hits中的hits数据
		SearchHits hits = response.getHits();
		System.out.println("一共搜索:" + hits.getTotalHits() + "条");
		// 获取数据遍历结果集
		try {
			SearchHit[] hit = hits.getHits();
			List<News> nList = new ArrayList<News>();
			for (SearchHit searchHit : hit) {
				// 解析当前document对应的product对象
				String nJson = searchHit.getSourceAsString();
				News newsSearch = MapperUtil.MP.readValue(nJson, News.class);
				News news = searchMapper.queryAllNews(newsSearch.getNid());
				nList.add(news);
			}
			return nList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
